package com.hx.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Huathy
 * @date 2021-10-20 21:39
 * @description
 */
@SuppressWarnings("all")
public class AioServer {
    private final int port;

    public static void main(String[] args) {
        new AioServer(8888);
    }

    public AioServer(int port) {
        this.port = port;
        listen();
    }

    private void listen() {
        try {
            ExecutorService executorService = Executors.newCachedThreadPool();
            AsynchronousChannelGroup channelGroup = AsynchronousChannelGroup.withThreadPool(executorService);
            // 工作线程，用来监听回调，时间相应的时候需要回调
            final AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open(channelGroup);
            server.bind(new InetSocketAddress(port));
            System.out.println("server is start, listen port : " + port);

            //准备接受数据
            server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
                final ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
                // 实现completed方法来回调
                // 由操作系统来触发
                // 回调有两个方法，一个成功，一个失败
                @Override
                public void completed(AsynchronousSocketChannel result, Object attachment) {
                    System.out.println("IO操作成功，开始获取数据..");
                    try {
                        buffer.clear();
                        result.read(buffer).get();
                        buffer.flip();
                        result.write(buffer);
                        buffer.flip();
                    } catch (ExecutionException | InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        try {
                            result.close();
                            server.accept(null,this);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("IO操作完成..");
                }

                @Override
                public void failed(Throwable exc, Object attachment) {
                    System.out.println("IO操作失败.由于：" + exc);
                }
            });
            Thread.sleep(Integer.MAX_VALUE);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
